package com.ias.agdis_r.activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.ias.agdis_r.R;
import com.ias.agdis_r.bean.update.UpadateApkBean;
import com.ias.agdis_r.manager.ActionManager;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.UpdateUtil;
import com.ias.agdis_r.util.flight.UiUtil;
import com.ias.agdis_r.util.sdcard.WriteLog;
import com.ias.agdis_r.view.box.BoxView;

/**
 * Activity基类，实现HTTP回调方法
 * @author zhangsc
 *
 */
public abstract class BaseActivity extends BaseKeyActivity{

	private Handler handler = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initContext();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initHandler();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		//TODO 页面不显示时，隐藏进度条
		hideProgress();
	}
	
	private void initContext()
	{
		if (DataBaseManager.getInstance() == null)
			new DataBaseManager(getApplicationContext());
	}

	/**
	 * 初始化用于更新UI的Handler
	 */
	private void initHandler()
	{
		handler = new Handler(Looper.myLooper()){    //为ACTIVITY生成一个Handler
			
			@Override
			public void handleMessage(Message msg) {
				
				Bundle bundle =msg.getData();
				String serviceId = bundle.getString("serviceId");
				Object object = bundle.getSerializable("response");
				
				// TODO 更新UI
				if(msg.what == ActionManager.UI_UPDATE)
				{
					String tnb = bundle.getString(MessageModel.TNB);
					if(S.isEmpty(tnb))
					{
						updateUI(serviceId);
					}
					else
					{
						updateUI(serviceId,tnb);
					}
				}
				// TODO RESPONSE应答处理
				else if(msg.what == ActionManager.UI_RESPONSE_SUCESS
						||msg.what == ActionManager.UI_RESPONSE_FAIL)
				{
					//如果是Response应答，调用Response回调
					if(object != null)
					{
						BaseResponse response = (BaseResponse) object;
						httpResponseExcute(serviceId,response); 
					}
				}
				// TODO 显示进度条
				else if(msg.what == ActionManager.UI_SHOW_PROGRESS)
				{
					 showProgress();
				}
				// TODO 隐藏进度条
				else if (msg.what == ActionManager.UI_HIDE_PROGRESS) {
					hideProgress();
				} else if (msg.what == ActionManager.UI_REFRESH_BOX) {
					sendBroadcast(new Intent(BoxView.BOX_REFRESH));
				}else if(msg.what == ActionManager.UI_SHOW_DIALOG_DOWNLOAD)
				{
					//对话框通知用户升级程序    
		    		showDialogDownLoad();  
				}
			}
			
		};
		
		//TODO 保存Activity的Handler对象，用于更新UI
		DataBaseManager.getInstance().setUIHandler(handler);
	}
	
	/**
	 * 显示进度条
	 */
	/**
	 * 
	 */
	protected void showProgress()
	{
		UiUtil.showLoadingUi2(this);
	}
	
	/**
	 * 隐藏进度条
	 */
	protected void hideProgress()
	{
		UiUtil.removeLoadingUiIfExist(this);
	}
	
	/**
	 * Http通讯结束后的处理
	 * 
	 */
	protected void httpResponseExcute(String serviceId,BaseResponse response) {
		
		try {
			
			if(response.getHeader().getStatus()==BaseResponseHeader.STATUS_FAILED)  //发送消息返回的状态值如果是失败
			{
				//TODO 失败处理,更新UI
				operateResponseFail(serviceId,response);  
			}
			else		//发送消息返回的状态值如果是成功
			{
				//TODO 成功处理，更新UI
				operateResponseSucess(serviceId,response);     
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//请求后，隐藏进度条
		hideProgress();
	}
	
	/**
	 * HTTP请求成功动作（返回消息中state不为0）
	 * 
	 */
	protected abstract void operateResponseSucess(String serviceId,BaseResponse response);
	
	/**
	 * HTTP请求失败动作（返回消息中state为0）
	 * 
	 */
	protected void operateResponseFail(String serviceId,BaseResponse response)
	{
		try {

				// 显示错误消息
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_TASK,
						response.getHeader().getErrorMessage(), false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//显示错误消息
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
					getString(R.string.receive_message_exception), false);
		}
	};
	
	/**
	 * 更新视图事件（用于接收到TCP消息以及普通刷新）
	 * @param tag
	 */
	protected abstract void updateUI(String tag);
	
	
	/**
	 * 更新视图事件（用于接收到TCP消息以及普通刷新）
	 * @param tag
	 * @param tnb
	 */
	protected void updateUI(String tag,String tnb)
	{
		this.updateUI(tag);
	};
	
	/**   
	 * 弹出对话框通知用户更新APK、配置文件   
	 *  
	 */  
	protected void showDialogDownLoad() {  
	    AlertDialog.Builder builer = new  Builder(BaseActivity.this);   
	    builer.setTitle(getString(R.string.upDateApp));
	    builer.setMessage(getString(R.string.upDateAppMessage));
	    //当点确定按钮时从服务器上下载 新的apk 然后安装    
	    builer.setPositiveButton(getString(R.string.confirm), new OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {  
	    		
	    		downLoadNewVersion();
	        }     
	    });  
	    //当点取消按钮时进行登录   
	    builer.setNegativeButton(getString(R.string.cancel), null);
	    AlertDialog dialog = builer.create();  
	    dialog.show();  
	} 
	
	/**
	 * 下载APK  
	 */
	protected void downLoadNewVersion() {  
		final ProgressDialog pd;    //进度条对话框   
	    pd = new  ProgressDialog(this);  
	    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
	    pd.setMessage(getString(R.string.downloading));
	    pd.show();  
	    new Thread(){  
	        @Override  
	        public void run() {  
	            try {  
	            	if(UpdateUtil.getInstance().getUpdateAPKList().size()>0)
	            	{
	            		for(UpadateApkBean updateInfo:UpdateUtil.getInstance().getUpdateAPKList())
	            		{
	            			UpdateUtil.getInstance().downloadAPK(updateInfo, pd);  
	            			sleep(1000);  
	            		}
	            	}
	            	//如果有需要升级的配置文件
	            	if(UpdateUtil.getInstance().getRemoteFileCount()>0)
	            	{
	            		UpdateUtil.getInstance().downLoadFtpFile(pd);
	            		//同步配置文件
	            		UpdateUtil.getInstance().initConfigFile();
	            	}
		            pd.dismiss(); //结束掉进度条对话框          
		            //暗装APK
		            installApk();   
	            } catch (Exception e) {  
	            	EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, getString(R.string.downloadFailed), false);
	                e.printStackTrace();  
	            }  
	        }}.start();  
	}
	
	/**
	 * 安装APK
	 */
	protected void installApk()
	{
		for(UpadateApkBean updateInfo:UpdateUtil.getInstance().getUpdateAPKList())
		{
			Intent intent = new Intent(Intent.ACTION_VIEW); 
			intent.setDataAndType(Uri.parse("file://" + updateInfo.getSavePath()),"application/vnd.android.package-archive"); 
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			WriteLog.getInstance().writeLog("安装APK:" + updateInfo.getSavePath());
			System.out.println("安装APK:" + updateInfo.getSavePath());
		}
	}
}
